package pt.ipbeja.eda;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main {
	private static boolean debug = true;
	
	private static byte[][] readPGMP2Image(String fileName) throws IOException {
            InputStream f = new FileInputStream(fileName);
            BufferedReader d = new BufferedReader(new InputStreamReader(f));
            d.readLine();    // first line contains P2
            String line = d.readLine();     // second line contains height and width but we need to deal with comments (start with #)
            while (line.startsWith("#")) {
                line = d.readLine();
            }
            Scanner s = new Scanner(line);
            int width = s.nextInt(); // get width from line
            int height = s.nextInt(); // get height from line
            line = d.readLine(); // third line contains maxVal
            s.close();
            s = new Scanner(line);
            int maxVal = s.nextInt();
            s.close();
            byte[][] image = new byte[height][width];

            int count = 0;
            int byteValue = 0;
            try {
                while (count < height*width) {
                    byteValue = d.read() ;
                    if ( byteValue < 0 ) 
                        break ;

                    if (byteValue != '\n') {
                        image[count / width][count % width] = (byte)byteValue ;
                        count++;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace(System.out) ;
            }
            if (debug) {
                System.out.println("Height=" + height);
                System.out.println("Width=" + height);
                System.out.println("Max Value=" + maxVal);
            }
            d.close();
            return image;

	}

	public static void main(String[] args)
	{
		try {
			byte[][] image = readPGMP2Image("peppersgrad.pgm");
		} catch (IOException e) {
			System.out.println("Erro ao ler a imagem");
			System.exit(0);
		}
	}

}
